/*
 * Anagram.java     1.0 Nov 4, 2013
 * 
 * An anagram is a word or a phrase that can be created by rearranging
 * the letters of another given word or phrase. We ignore white spaces and
 * letter case.
 * 
 * The all letters of "Desperation" can be rearranged to the phrase "A Rope
 * Ends It".
 * 
 * The program should receive input of two strings and give the output to
 * screen telling whether these words are anagrams
 */


public class Anagram {
    public static void main(String[] args) {
        String firstPhrase
            = Commons.getStringWithPrompt(Messages.ENTER_FIRST_STRING);
        String secondPhrase
            = Commons.getStringWithPrompt(Messages.ENTER_SECOND_STRING);

        // simple check
        if ((firstPhrase.length() == 0) || (secondPhrase.length() == 0)) {
            Commons
                .terminateProgramWithMessage(Messages.STRING_MUST_BE_NOT_EMPTY);
        }

        System.out.println(
                isAnagram(firstPhrase, secondPhrase)
                    ?Messages.IS_ANAGRAM:Messages.NOT_ANAGRAM);
    }

    public static boolean isAnagram(String firstPhrase, String secondPhrase) {
        for (int i = 0; i < firstPhrase.length(); i++) {
            char charAtI = firstPhrase.charAt(i);
            boolean charCountAreNotEqual = (charAtI != ' ')
                && (countChars(charAtI, firstPhrase) 
                        != countChars(charAtI, secondPhrase));

            if (charCountAreNotEqual) {
                return false;
            }
        }  

        return true;
    }

    public static int countChars(char ch, String str) {
        int count = 0;

        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                count++;
            }
        }

        return count;
    }
}

